package org.springframework.security.oauth2.server.authorization.web;

import org.springframework.core.convert.converter.Converter;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2PasswordAuthenticationToken;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;

import javax.servlet.http.HttpServletRequest;

/**
 * 新增
 * 支持密码模式
 */
public  class PasswordAuthenticationConverter implements Converter<HttpServletRequest, Authentication> {


    protected AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource();//add by chenyc

        public PasswordAuthenticationConverter() {
        }

        public Authentication convert(HttpServletRequest request) {
            String grantType = request.getParameter("grant_type");
            if (!AuthorizationGrantType.PASSWORD.getValue().equals(grantType)) {
                return null;
            } else {
                Authentication clientPrincipal = SecurityContextHolder.getContext().getAuthentication();
                if(!(clientPrincipal instanceof OAuth2ClientAuthenticationToken)){//必须事先AuthorizationGrantType.CLIENT_CREDENTIALS认证
                    return null;
                }
                String userid=request.getParameter("userid");
                String password=request.getParameter("password");
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken=new UsernamePasswordAuthenticationToken(userid,password);

                usernamePasswordAuthenticationToken.setDetails(authenticationDetailsSource.buildDetails(request));
                OAuth2PasswordAuthenticationToken oAuth2PasswordAuthenticationToken=new OAuth2PasswordAuthenticationToken((OAuth2ClientAuthenticationToken) clientPrincipal,usernamePasswordAuthenticationToken);
                return oAuth2PasswordAuthenticationToken;
            }
        }
    }